package com.bananascrum.pages;

import static org.testng.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public abstract class Page {

	protected static WebDriver driver;
	protected static String pageUrl = "http://demo.bananascrum.com";

	public Page(WebDriver driver) {
		driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
		Page.driver = driver;
	}

	protected void open() {
		driver.get(pageUrl);
	}

	protected void assertTextPresent(By by, String text) {
		WebElement element = driver.findElement(by);
		assertEquals(text, element.getText());
	}

	protected void checkPageTitle(String address) {
		assertEquals(address, driver.getTitle());
	}

	protected static void insertText(By by, String text) {
		WebElement element = driver.findElement(by);
		element.clear();
		element.sendKeys(text);
	}

	protected boolean isTextPresent(String expected) {
		String pageSource = driver.getPageSource();
		return pageSource.contains(expected);
	}

	protected boolean isElementPresent(By by) throws Exception {
		for (int i = 0; i < 10; i++) {
			try {
				driver.findElement(by);
				return true;
			} catch (NoSuchElementException e) {
				driver.wait(1000);
			}
		}
		return false;
	}

	void click(By by) {
		WebElement element = driver.findElement(by);
		element.click();
	}
}